// pages/goods_x/goods_x.js
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        indicatorDots: false,
        autoplay: true,
        interval: 5000,
        duration: 1000,

        course_id: '',

        success_modal: '',

        all_userids: '',
        in_userids: '',

        sign_text: '签到',
        sign_info: {},
        sign_type: 1,

        summary_file_url: '',
        is_notice: '2',// 是否发送微信通知，1发送，2不发送

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            user: app.globalData.user,
            course_id: options.course_id
        })
        this.getSignInOut()
        this.getSummaryFile()
        this.getCourseDetail();
        if(this.data.user.role==2){
            this.getCourseAttendance();
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    //获取课程详情
    getCourseDetail: function() {
        let _this = this,
            course_id = _this.data.course_id;
        app._get('/api/login/course/getCourseDetail', {
            course_id: course_id
        }, function(response) {
            let setdata = {};
            setdata['course'] = response.data.data;
            setdata['all_userids'] = response.data.data.all_userids;
            _this.setData(setdata);
        })
    },

    //获取课程考勤详情
    getCourseAttendance: function() {
        let _this = this,
            course_id = _this.data.course_id;
        app._get('/api/login/course/getCourseAttendance', {
            course_id: course_id
        }, function(response) {
            if(response.data.data!=null){
                let setdata = {};
                setdata['in_userids'] = response.data.data.in_userids;
                _this.setData(setdata);
            }
        })
    },

    //学生选课
    addUserTime: function() {
        let _this = this;
        let course_id = _this.data.course_id;
        let course = _this.data.course;
        app._post('/api/login/student/addUserTime', {
            course_id: course_id,
            teacher_id: course.teacher_id,
            time: course.time,
        }, function(response) {
            if (response.data.code == 200) {
                _this.setData({
                    success_modal: 'show',
                })
            }
        })
    },

    //考勤
    addStudent: function (e) {
        let user_id = e.currentTarget.dataset.user_id;
        let in_userids= this.data.in_userids;
        if(in_userids.indexOf(user_id)>=0)
        {
            const in_userids = this.data.in_userids.replace(user_id,'')
            this.setData({
                in_userids: in_userids
            })
        }
        else
        {
            const in_userids = this.data.in_userids.concat(','+user_id)
            this.setData({
                in_userids: in_userids
            })
        }
    },

    // 预点名-弹窗显示缺勤学生
    preAddAttendance: function() {
      let _this = this;
      let in_userids = _this.data.in_userids;
      let all_students = _this.data.course.student
      let queqin = ''
      // 弹窗显示缺勤学生
      for(let student of all_students) {
        if(in_userids.indexOf(student.user_id+'') == -1) {
          queqin = queqin.concat(','+student.realname)
        }
      }
      wx.showModal({
        title: '缺勤学生',
        content: queqin,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            _this.notice()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },

    // 弹窗确认是否发送考勤通知
    notice: function () {
      let _this = this
      wx.showModal({
        title: '提示',
        content: '是否发送考勤通知？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            _this.setData({
              is_notice: '1'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
            _this.setData({
              is_notice: '2'
            })
          }

          _this.addAttendance()
        }
      })
    },

    /**
     * 点名
     */
    addAttendance: function() {
        let _this = this;
        let course_id = _this.data.course_id;
        let all_userids = _this.data.all_userids;
        let in_userids = _this.data.in_userids;
        let time = _this.data.course.time;
        if (in_userids == '') {
            wx.showToast({
                title: '请在点名表中选择学生',
                icon: 'none'
            })
            return false;
        }
        app._post('/api/login/teacher/addCourseAttendance', {
            course_id: course_id,
            all_userids: all_userids,
            in_userids: in_userids,
            time: time,
            is_notice: _this.data.is_notice,
        }, function(response) {
            wx.showToast({
              title: '点名成功',
              icon: 'none'
            })
            
        })
    },

    //预览图片，放大预览
    preview(e) {
        wx.previewImage({
            current: e.target.dataset.imgurl, // 当前显示图片的http链接
            urls: [e.target.dataset.imgurl] // 需要预览的图片http链接列表
        })
    },


    //图片点击事件
    imgYu: function(event) {
        var that = this
        var img = event.currentTarget.dataset.src;
        var index = event.currentTarget.dataset.id;
        wx.previewImage({
            current: img[index],
            urls: [img]
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
            title: "课程《" + this.data.course.name + "》推荐给您~",
            imageUrl: app.domain + this.data.course.logo,
        }
    },

    //确定后
    confirm(){
        wx.switchTab({
            url: '/pages/user/user',
        })
    },

    //去所有评价
    toComment: function(e){
        wx.navigateTo({
            url: '/pages/comment/comment?course_id='+e.currentTarget.dataset.course_id,
        })
    },

    getSignInOut: function() {
        let _this = this
        let course_id = _this.data.course_id;
        app._post('api/userSignIn/getUserSignInfo', {
            course_id: course_id,
        }, function(response) {
            if (response.data.code == 200) {
                _this.setData({
                    sign_info: response.data.data,
                })
                if(response.data.data.sign_in) {
                    _this.setData({
                        sign_type: 2,
                        sign_text: '签退',
                    })
                }
            }
        })
    },

    signInOut: function(iamge_url) {
        let _this = this
        let course_id = _this.data.course_id;
        app._post('api/userSignIn/userSignIn', {
            iamge_url: iamge_url,
            course_id: course_id,
            type: _this.data.sign_type,
        }, function(response) {
            if (response.data.code == 200) {
                wx.showModal({
                    title: '提示',
                    content: '操作成功',
                    showCancel: false
                })
            }
        })
    },

    signInOutPic: function() {
        let _this = this
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            maxDuration: 30,
            camera: 'back',
            success(res) {
                console.log(res)
                console.log(res.tempFiles[0].tempFilePath)
                console.log(res.tempFiles[0].size)
                wx.uploadFile({
                    url: 'https://www.zhuotengedu.com/admin/course_interest/?s=admin/api.plugs/plupload', //后端接口
                    filePath: res.tempFiles[0].tempFilePath,
                    name: 'file',
                    success(res) {
                        console.log(res)
                        if (res.statusCode != 200) {
                            wx.showModal({
                                title: '提示',
                                content: '操作失败',
                                showCancel: false
                            });
                            return;
                        } else {
                            let uploadData = JSON.parse(res.data)
                            _this.signInOut(uploadData.url)
                        }
                    },
                    fail(e) {
                        console.log(e)
                        wx.showModal({
                            title: '提示',
                            content: '操作失败',
                            showCancel: false
                        });
                    },
                    complete() {
                        wx.hideToast(); //隐藏Toast
                    }
                })
            }
        })
    },

    // 总结资料上传
    addFile: function() {
      var _this = this;
      wx.chooseMessageFile({
        count: 1,
        type: 'all',
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片
          // const tempFilePaths = res.tempFiles
          console.log(res)
          const tempFilePaths = res.tempFiles[0].path;
          wx.uploadFile({
              header: {
                  token: wx.getStorageSync('token'),
                  "Content-Type": "json"
              },
              url: app.domain + '/api/file/ossupload',
              filePath: tempFilePaths,
              name: 'file',
              success(response) {
                  let data = JSON.parse(response.data);
                  if (data.code !== 1) {
                      wx.showToast({
                          title: data.msg,
                          icon: 'none'
                      })
                  }
                  console.log(data)
                  _this.setData({
                      summary_file_url: data.data.site_url,
                  })
                  _this.summaryFile(data.data.site_url)

              },
              fail(err) {
                  console.log(err)
              }
          })
        }
      })
  },

  summaryFile: function(file_url) {
    let _this = this
    let course_id = _this.data.course_id;
    app._post('api/user_summary/summary', {
        file_url: file_url,
        course_id: course_id,
    }, function(response) {
        if (response.data.code == 200) {
            wx.showModal({
                title: '提示',
                content: '操作成功',
                showCancel: false
            })
        }
    })
},

getSummaryFile: function() {
  let _this = this
  let course_id = _this.data.course_id;
  app._post('api/user_summary/getSummary', {
      course_id: course_id,
  }, function(response) {
      if (response.data.code == 200) {
        if(response.data.data && response.data.data.file_url){
          _this.setData({
            summary_file_url: response.data.data.file_url
          })
        }else{
          _this.setData({
            summary_file_url: ''
          })
        }
          
      }
  })
},

    // 随机生成文件名
    getFileName (m) {
        m = m > 13 ? 13 : m;
        var num = new Date().getTime();
        return num.toString().substring(13 - m);
    },
})